package com.nhutcm.sms.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;

import com.nhutcm.sms.Utils.AppApplication;
import com.nhutcm.sms.Utils.Constant;
import com.nhutcm.sms.Utils.HttpUtils;
import com.nhutcm.sms.Utils.InternetUtils;
import com.nhutcm.sms.Utils.LogUtils;
import com.nhutcm.sms.Utils.LogUtils.Level;
import com.nhutcm.sms.activity.MainActivity;
import com.nhutcm.sms.model.SMSClass;
import com.nhutcm.sms.network.SMSBroadcastingNetwork;

public class SMSBroadcastingService extends IntentService {

	public static final String TAG = "SMSBroadcastingService";
	public static String SMS_KEY = "SMS_KEY";
	Activity mActivity;

	public SMSBroadcastingService() {
		super("SMSBroadcastingService");
	}

	// SystemClock.sleep(30000); // 30 seconds, pretend to do work
	@Override
	protected void onHandleIntent(Intent intent) {
		if (!Constant.SERVER_ON) {
			return;
		}
		Bundle b = intent.getExtras();
		if (b != null) {
			int reqCode = b.getInt(SMSBroadcastingNetwork.REQ_CODE);
			if (reqCode != Constant.SEND_SMS) {
				boolean isConnect = InternetUtils
						.isConnectingToInternet(getActivity());
				if (!isConnect) {
					LogUtils.write(Level.ERROR, "No internet connection");
					return;
				}
			}

			switch (reqCode) {
			case Constant.PING_REQ_CODE:
				sendPingReq(Constant.PING_REQ);
				break;

			case Constant.GET_LIST_NUM_REQ_CODE:
				sendGetListReq(Constant.GET_LIST_NUM_REQ);
				break;

			case Constant.UPDATE_STATUS_CODE:
				ArrayList<String> arr = b
						.getStringArrayList(SMSBroadcastingNetwork.UPDATE_ARRAY);
				updateStatus(arr);
				break;

			case Constant.FORWARD_MESSAGE_CODE:
				ArrayList<String> arrSMS = b
						.getStringArrayList(SMSBroadcastingNetwork.SMS_ARRAY);
				forwardSMS(arrSMS);
				break;

			case Constant.SEND_SMS:
				SMSClass sms = (SMSClass) b
						.getSerializable(SMSBroadcastingNetwork.SMS_VALUE);
				sleep(Constant.WAITING_SEND_SMS);
				sendSMS(sms);
				break;

			case Constant.POINT_MESS:
				sleep(Constant.WAITING_SEND_SMS);
				MainActivity activity = (MainActivity) getActivity();
				activity.onPointCallback();
				break;

			default:
				break;
			}

		}

	}

	private void sendGetListReq(String url) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("key", Constant.TOKEN));

		String result = HttpUtils.requestHttpPOST(url, params);
		if (result == null) {
			LogUtils.write(Level.ERROR, "[sendGetListReq] - Throw Exception");
			return;
		}
		Log.i(TAG, result);
		MainActivity activity = (MainActivity) getActivity();
		activity.onGetListResult(result);
	}

	private void sendPingReq(String url) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("key", Constant.TOKEN));

		String result = HttpUtils.requestHttpGET(url);
		if (result == null) {
			LogUtils.write(Level.ERROR, "[sendPingReq] -Throw Exception");
			return;
		}
		Log.i(TAG, result);
	}

	private void updateStatus(ArrayList<String> list) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("key", Constant.TOKEN));
		params.add(new BasicNameValuePair("smsno", list.get(0)));
		params.add(new BasicNameValuePair("phone", list.get(1)));
		params.add(new BasicNameValuePair("status", list.get(2)));

		String result = HttpUtils.requestHttpPOST(Constant.UPDATE_STATUS,
				params);
		if (result == null) {
			LogUtils.write(Level.ERROR, "[updateStatus] -Throw Exception");
			return;
		}
		Log.i(TAG, result);
	}

	private void forwardSMS(ArrayList<String> list) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("key", Constant.TOKEN));
		params.add(new BasicNameValuePair("phone", list.get(0)));
		params.add(new BasicNameValuePair("message", list.get(1)));

		String result = HttpUtils.requestHttpPOST(Constant.FORWARD_MESSAGE,
				params);
		if (result == null) {
			LogUtils.write(Level.ERROR, "[forwardSMS] -Throw Exception");
			return;
		}
		Log.i(TAG, result);
	}

	private void sendSMS(SMSClass smsObject) {
		String strPhoneNumber = smsObject.getPhone();
		String strContent = smsObject.getMessage();
		//strContent = "It’s been offensive since day one,It’s been offensive since day one,It’s been offensive since day one,It’s been offensive since..abcde";

		if (strPhoneNumber.equals("") || strContent.equals("")) {
			return;
		}

		Intent i = new Intent("SMS_SENT");
		i.putExtra(SMS_KEY, smsObject);

		PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, i,
				PendingIntent.FLAG_UPDATE_CURRENT);

		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(strPhoneNumber, null, strContent, sentPI, null);
	}

	private Activity getActivity() {
		if (mActivity == null) {
			Context context = ((AppApplication) getApplicationContext())
					.getCurrentCtx();
			mActivity = (MainActivity) context;
		}
		return mActivity;
	}

	void sleep(int time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			Log.e(TAG, e.getMessage());
		}
	}

}
